<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small"
          placeholder="输入员工姓名全员搜索" v-model="queryParmas.keyword" @input="changeValue" />
        <!-- 树形组件 -->
        <el-tree :data="treeData" :props="defaultProps" default-expand-all :expand-on-click-node="false"
          highlight-current ref="deptTree" node-key="id" @current-change="selectNode">

        </el-tree>
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel" >excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeeList">
          <el-table-column label="头像" align="center" prop="staffPhoto">
            <template v-slot="{ row }">
              <el-avatar :size="30" :src="row.staffPhoto" v-if="row.staffPhoto"></el-avatar>
              <span v-else class="username"> {{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username">
          </el-table-column>
          <el-table-column label="手机号" sortable prop="mobile">
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber">
          </el-table-column>
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName">
          </el-table-column>
          <el-table-column label="入职时间" sortable prop="timeOfEntry">
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template v-slot="{ row }">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm confirm-button-text='确定' cancel-button-text='取消' icon="el-icon-info" icon-color="red"
                title="是否删除吗？" @onConfirm="confirmDel(row.id)"> 
                <!-- 需要onConfirm才能触发 -->
                <el-button type="text" size="mini" slot="reference" style="padding: 10px;">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px;">
          <el-pagination layout="total ,prev, pager, next" :total="total"
            @current-change="handleCurrentChange"></el-pagination>

        </el-row>
      </div>
    </div>
    <!-- 放置导入组件 -->
    <import-excel :showExcelDialog.sync="showDialog" @uploadSuccess="getEmployeeList"></import-excel>
    <!-- 弹层组件 -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色" >
      <!-- 弹层组件 -->
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name  }}</el-checkbox>

      </el-checkbox-group>
      <!-- 确定和取消按钮 -->
       <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">

          <el-button size="mini" type="primary" @click="btnRoleOk"> 确定</el-button>
          <el-button size="mini" @click="showRoleDialog=falses"> 取消</el-button>

        </el-col>
       </el-row>

    </el-dialog>
  </div>
</template>

<script>
import { getDepartment } from '@/api/department';
import { getEmployeeList,
         exportEmployee,
         delEmployee,
         getRoleList,
         getEmployeeDetail,
         assignRoles
        } from '@/api/employee';
import FileSaver from 'file-saver';
import { transListToTreeData } from '@/utils';
import ImportExcel from './components/import-excel.vue';
export default {
  name: 'Employee',
  components:{
    ImportExcel
  },
  data() {
    return {
      roleList:[],
      roleIds:[], // 存储角色id ，用于双向绑定
      total: 0,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 存储查询参数
      queryParmas: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''

      },
      employeeList: [], // 记录员工数据
      showDialog: false,  // 控制弹层显示
      showRoleDialog:false, // 控制角色弹层显示
      currentUserId:null,
    }
  },
  created() {
    this.getDepartList()
  },
  methods: {
    // 获取部门列表
    async getDepartList() {
      // 递归方法，将数据转化为树形结构
      this.treeData = transListToTreeData(await getDepartment(), 0)
      this.queryParmas.departmentId = this.treeData[0].id
      // 树组件的渲染是异步的
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParmas.departmentId)
      })
      this.getEmployeeList()
    },
    //树形组件的点击事件
    selectNode(node) {
      this.queryParmas.page = 1
      this.queryParmas.departmentId = node.id
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParmas)
      this.employeeList = rows
      this.total = total
    },
    // 切换分页
    handleCurrentChange(val) {
      this.queryParmas.page = val
      this.getEmployeeList()
    },
    // 输入值内容时触发
    changeValue() {
      // 单位时间内只会触发一次
      clearTimeout(this.timer) //清理上一次的定时器
      setTimeout(() => {
        this.queryParmas.page = 1
        this.getEmployeeList()
      }, 400);
    },
    // 导出excel
    async exportExcel() {
      // 1. 调用导出员工的接口
      // 二进制流blob
      const res = await exportEmployee()

      // 2. fileSaver 下载
      // FileSaver.saveAs(二进制流数据, 文件名)
      FileSaver.saveAs(res, '员工数据.xlsx')
    },
    // 删除员工
    async confirmDel(id) {
      await delEmployee(id)
      this.$message.success('删除成功')
      if (this.employeeList.length === 1&&this.queryParmas.page>1) {
        this.queryParmas.page--
      }
      this.getEmployeeList()
    },
    // 点击角色弹出层
    async btnRole(id){
      
      this.roleList = await getRoleList()
      // 记录当前点击的id 因为后边 确定取消要存取对应的用户
      this.currentUserId=id
      const {roleIds} = await getEmployeeDetail(id)
      this.roleIds= roleIds 
      this.showRoleDialog=true
    },
    // 点击角色确定
    async btnRoleOk(){
      await assignRoles({
        id:this.currentUserId,
        roleIds:this.roleIds
      })
      this.$message.success('分配角色成功')
      this.showRoleDialog=false
    }

  }


}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .pic_str {
    border-radius: 50%;
    background-color: #09bcfd;
    color: #f1de0e;
    display: inline-block;
    width: 40px;
    height: 40px;
    line-height: 40px;

  }

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>